package com.wangyu.springsecuritydemo.service.security;

import com.wangyu.springsecuritydemo.entity.primary.RoleEntity;
import com.wangyu.springsecuritydemo.entity.primary.UserEntity;
import com.wangyu.springsecuritydemo.service.RoleService;
import com.wangyu.springsecuritydemo.service.UserService;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 自定义用户信息，查询数据库，验证账号，并查询出相关权限(角色信息)
 *
 * @Author wangyu
 * @Date 2019/2/18 15:52
 * @Version 1.0
 */
public class UserSecurityDetailsService implements UserDetailsService {

  @Autowired
  private UserService userService;

  @Autowired
  private RoleService roleService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserEntity currentUser = userService.findByUserName(username);
    if (currentUser == null) {
      throw new UsernameNotFoundException("未发现指定账号，或者账号状态不正确");
    }

    //查询用户角色信息
    List<RoleEntity> roles = null;
    roles = roleService.findByUserId(currentUser.getId());
    if (roles == null || roles.isEmpty()) {
      throw new UsernameNotFoundException("用户权限状态错误");
    }
    List<SimpleGrantedAuthority> authorities = new LinkedList<>();
    for (RoleEntity role : roles) {
      SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getName());
      authorities.add(authority);
    }

    //生成UserDetails对象并返回
    UserDetails userDetails = new User(username, currentUser.getPassword(), authorities);
    return userDetails;
  }
}
